<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_request_method()
{
	return $_SERVER['REQUEST_METHOD'];
}

function otx_request_is_post()
{
	return otx_request_method() == 'POST';
}

function otx_request_is_secure()
{
	return otx_request_scheme() == 'https';
}

function otx_request_raw_body()
{
	static $raw_body = null;

	if (null === $raw_body) {
		$body = file_get_contents('php://input');

		if (strlen(trim($body)) > 0) {
			$raw_body = $body;
		} else {
			$raw_body = false;
		}
	}

    return $raw_body;
}

function otx_request_scheme()
{
	return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
}

function otx_request_http_host()
{
	if (isset($_SERVER['HTTP_HOST'])) {
		return $_SERVER['HTTP_HOST'];
	}

	$scheme = otx_request_scheme();

	if (($scheme == 'http' && $_SERVER['SERVER_PORT'] == 80) ||
		($scheme == 'https' && $_SERVER['SERVER_PORT'] == 443)) {
		return $_SERVER['SERVER_NAME'];
	} else {
		return $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
	}
}

function otx_request_client_ip()
{
	if (isset($_SERVER['HTTP_CLIENT_IP'])) {
		return $_SERVER['HTTP_CLIENT_IP'];
	} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		return $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else if (isset($_SERVER['REMOTE_ADDR'])) {
		return $_SERVER['REMOTE_ADDR'];
	} else {
		return null;
	}
}

function otx_request_uri()
{
	if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
		// IIS with Microsoft Rewrite Module
		$request_uri = $_SERVER['HTTP_X_ORIGINAL_URL'];
	} else if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
		// IIS with ISAPI_Rewrite
		$request_uri = $_SERVER['HTTP_X_REWRITE_URL'];
	} else if (
			// IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
			isset($_SERVER['IIS_WasUrlRewritten'])
			&& $_SERVER['IIS_WasUrlRewritten'] == '1'
			&& isset($_SERVER['UNENCODED_URL'])
			&& $_SERVER['UNENCODED_URL'] != ''
	) {
		$request_uri = $_SERVER['UNENCODED_URL'];
	} else if (isset($_SERVER['REQUEST_URI'])) {
		$request_uri = $_SERVER['REQUEST_URI'];
		// Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
		$scheme_host = otx_request_scheme() . '://' . otx_request_http_host();
		if (strpos($request_uri, $scheme_host) === 0) {
			$request_uri = substr($request_uri, strlen($scheme_host));
		}
	} else if (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
		$request_uri = $_SERVER['ORIG_PATH_INFO'];
		if (!empty($_SERVER['QUERY_STRING'])) {
			$request_uri .= '?' . $_SERVER['QUERY_STRING'];
		}
	} else {
		$request_uri = null;
	}
	return $request_uri;
}

function otx_request_base_url()
{
	$filename = (isset($_SERVER['SCRIPT_FILENAME'])) ? basename($_SERVER['SCRIPT_FILENAME']) : '';

	if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $filename) {
		$base_url = $_SERVER['SCRIPT_NAME'];
	} elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $filename) {
		$base_url = $_SERVER['PHP_SELF'];
	} elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $filename) {
		$base_url = $_SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility
	} else {
		// Backtrack up the script_filename to find the portion matching
		// php_self
		$path    = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '';
		$file    = isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : '';
		$segs    = explode('/', trim($file, '/'));
		$segs    = array_reverse($segs);
		$index   = 0;
		$last    = count($segs);
		$base_url= '';
		do {
			$seg     = $segs[$index];
			$base_url= '/' . $seg . $base_url;
			++$index;
		} while (($last > $index) && (false !== ($pos = strpos($path, $base_url))) && (0 != $pos));
	}

	// Does the baseUrl have anything in common with the request_uri?
	$request_uri = otx_request_uri();

	if (0 === strpos($request_uri, $base_url)) {
		// full $baseUrl matches
		return $base_url;
	}

	if (0 === strpos($request_uri, dirname($base_url))) {
		// directory portion of $baseUrl matches
		return rtrim(dirname($base_url), '/');
	}

	$truncatedRequestUri = $request_uri;
	if (($pos = strpos($request_uri, '?')) !== false) {
		$truncatedRequestUri = substr($request_uri, 0, $pos);
	}

	$basename = basename($base_url);
	if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
		// no match whatsoever; set it blank
		return '';
	}

	// If using mod_rewrite or ISAPI_Rewrite strip the script filename
	// out of baseUrl. $pos !== 0 makes sure it is not matching a value
	// from PATH_INFO or QUERY_STRING
	if ((strlen($request_uri) >= strlen($base_url))
		&& ((false !== ($pos = strpos($request_uri, $base_url))) && ($pos !== 0)))
	{
		$base_url = substr($request_uri, 0, $pos + strlen($base_url));
	}

	return rtrim($base_url, '/');
}

function otx_request_base_path()
{
	$filename = (isset($_SERVER['SCRIPT_FILENAME'])) ? basename($_SERVER['SCRIPT_FILENAME']) : '';

	$base_url = otx_request_base_url();
	if (empty($base_url)) {
		return '';
	}

	if (basename($base_url) === $filename) {
		$base_path = dirname($base_url);
	} else {
		$base_path = $base_url;
	}

	if (substr(PHP_OS, 0, 3) === 'WIN') {
		$base_path = str_replace('\\', '/', $base_path);
	}

	return rtrim($base_path, '/');
}

function otx_request_append_query($url, $key, $value = null)
{
	if (is_array($key)) {
		foreach ((array) $key as $k => $v) {
			$url = otx_request_append_query($url, $k, $v);
		}
		return $url;
	}

	$key = urlencode($key);
	$value = urlencode($value);

	$pos = strpos($url, '#');
	if (false !== $pos) {
		$fragment = substr($url, $pos + 1);
		$url = substr($url, 0, $pos);
	} else {
		$fragment = '';
	}

	$pos = strpos($url, '?');
	if (false !== $pos) {
		$query = substr($url, $pos + 1);
		$url = substr($url, 0, $pos);
	} else {
		$query = '';
	}

	$exists = false;
	$query = explode('&', $query);
	foreach ($query as $i => $s) {
		if (substr($s, 0, strlen($key) + 1) == $key . '=') {
			$query[$i] = $key . '=' . $value;
			$exists = true;
			break;
		}
	}

	if (!$exists) {
		$query[] = $key . '=' . $value;
	}

	return $url . '?' . implode('&', $query)
			. (!empty($fragment) ? '#' . $fragment : '');
}